﻿using System.Collections.Generic;
using WikiPlex;
using WikiPlex.Compilation.Macros;
using WikiPlex.Parsing;

namespace WikiMaml.Augmenters
{
    /// <summary>
    /// Handles augmenting the scopes for the <see cref="TableMacro"/>.
    /// </summary>
    public class TableScopeAugmenter : WikiPlex.Parsing.TableScopeAugmenter
    {
        /// <summary>
        /// Overidden. This will insert new, remove, or re-order scopes.
        /// </summary>
        /// <param name="macro">The current macro.</param>
        /// <param name="capturedScopes">The list of captured scopes.</param>
        /// <param name="content">The wiki content being parsed.</param>
        /// <returns>
        /// A new list of augmented scopes.
        /// </returns>
        public override IList<Scope> Augment(IMacro macro, IList<Scope> capturedScopes, string content)
        {
            IList<Scope> scopes = base.Augment(macro, capturedScopes, content);
            IList<Scope> augmentedScopes = new List<Scope>(scopes.Count);

            for (int i = 0; (i + 1) < scopes.Count; i++)
            {
                Scope current = scopes[i];
                Scope peek = scopes[i + 1];

                augmentedScopes.Add(current);

                if (peek.Name == ScopeName.TableRowHeaderBegin && current.Name == ScopeName.TableBegin)
                    augmentedScopes.Add(new Scope(MamlScopeName.TableHeaderBegin, current.Index, current.Length));
                else if (current.Name == ScopeName.TableRowHeaderEnd)
                    augmentedScopes.Add(new Scope(MamlScopeName.TableHeaderEnd, current.Index + current.Length));
            }

            // explicitly add the last scope as it was intentionally skipped
            Scope last = scopes[scopes.Count - 1];
            augmentedScopes.Add(last);

            return augmentedScopes;
        }
    }
}
